package com.hbyj.struts.action;

import gnu.io.SerialPort;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.hbyj.db.function.DbTools;
import com.hbyj.gps.SerialReader;
import com.hbyj.hbm.vo.Jbqk01;
import com.hbyj.hbm.vo.YjdcYjdc01;
import com.hbyj.hbm.vo.YjdcYjdc06;
import com.hbyj.util.ChangeTool;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.rtf.RtfWriter2;
import com.opensymphony.xwork2.ActionSupport;

public class YjdcdHandleBenjiAction extends ActionSupport{
	
	//对象
	private YjdcYjdc01 yjdc01;
	
	private File qmlj;
	private File jubu1;
	private File jubu2;
	

	public YjdcYjdc01 getYjdc01() {
		return yjdc01;
	}

	public void setYjdc01(YjdcYjdc01 yjdc01) {
		this.yjdc01 = yjdc01;
	}

	public File getQmlj() {
		return qmlj;
	}

	public void setQmlj(File qmlj) {
		this.qmlj = qmlj;
	}

	public File getJubu1() {
		return jubu1;
	}

	public void setJubu1(File jubu1) {
		this.jubu1 = jubu1;
	}

	public File getJubu2() {
		return jubu2;
	}

	public void setJubu2(File jubu2) {
		this.jubu2 = jubu2;
	}


	public void insertYjdcdForPbBenji() throws UnsupportedEncodingException, IOException{
		HttpServletRequest request = ServletActionContext.getRequest();
		String jbqk0102 = request.getParameter("jbqk0102");
		String yjdc01000 = request.getParameter("yjdc01000");
		String yjdc01140 = request.getParameter("yjdc01140");
		String yjdc01330 = request.getParameter("yjdc01330");
		yjdc01.setYjdc01000(yjdc01000);
		yjdc01.setYjdc01140(yjdc01140);
		yjdc01.setYjdc01330(yjdc01330);
		yjdc01.setJbqk0102(jbqk0102);
		yjdc01.setYjdc01380("false");
		//对图片的处理
		if(qmlj!=null){
			String newFileName = changeFileName();
			if(uploadFile(newFileName,qmlj)){//上传成功之后
				yjdc01.setYjdc01300(newFileName);
			}
		}
		if(jubu1!=null){
			String newFileName = changeFileName();
			if(uploadFile(newFileName,jubu1)){//上传成功之后
				yjdc01.setYjdc01310(newFileName);
			}
		}
		if(jubu2!=null){
			String newFileName = changeFileName();
			if(uploadFile(newFileName,jubu2)){//上传成功之后
				yjdc01.setYjdc01320(newFileName);
			}
		}
		YjdcYjdc06 yjdc06 = new YjdcYjdc06();
		yjdc06.setYjdc06000(yjdc01.getYjdc01000());
		yjdc06.setYjdc06010("00");
		yjdc06.setYjdc06080(yjdc01.getYjdc01270());
		yjdc06.setJbqk0102(yjdc01.getJbqk0102());
		if(DbTools.saveObj(yjdc01)&&DbTools.saveObj(yjdc06)){
			ServletActionContext.getResponse().getOutputStream().write("true".getBytes("utf-8"));
		}else{
			ServletActionContext.getResponse().getOutputStream().write("false".getBytes("utf-8"));
		}
	}
	

	
	public void queryYJDCDByKeyWord() throws UnsupportedEncodingException, IOException{
		HttpServletRequest request = ServletActionContext.getRequest();
		String lyCode = request.getParameter("lyCode");
		String keyword = request.getParameter("keyword");
		String hql = "select JBQK0100,JBQK0110,JBQK0102 from JBQK01 where JBQK0100 like '"+lyCode+"' And JBQK0110 like '%"+keyword+"%'";
		List list = DbTools.findBySql(hql);
		if(list.size()>0){
			JSONArray jsonArray = new JSONArray();
			for(int i=0;i<list.size();i++){
				JSONObject obj = new JSONObject();
				Object[] object = (Object[]) list.get(i);
				obj.accumulate("id",object[0]);
				obj.accumulate("name",object[1]);
				obj.accumulate("biaoshi", object[2]);
				//拿到经度，纬度，高度
				//String jwg = getJWDAndGD();
				String jwg = "110.1,20.1,10";
				obj.accumulate("jwg", jwg);
				jsonArray.add(obj);
			}
			ServletActionContext.getResponse().getOutputStream().write(jsonArray.toString().getBytes("utf-8"));
		}
	}
	
	public String getJWDAndGD(){
		String jwg = "";
		 HashMap<String, Comparable> params = new HashMap<String, Comparable>();
	     params.put( SerialReader.PARAMS_PORT, "COM5" ); // 端口名称
	     params.put( SerialReader.PARAMS_RATE, 9600 ); // 波特率
	     params.put( SerialReader.PARAMS_TIMEOUT, 1000); // 设备超时时间 1秒
	     params.put( SerialReader.PARAMS_DELAY, 1000 ); // 数据准备端口时间 1秒
	     params.put( SerialReader.PARAMS_DATABITS, SerialPort.DATABITS_8 ); // 数据位
	     params.put( SerialReader.PARAMS_STOPBITS, SerialPort.STOPBITS_1 ); // 停止位
	     params.put( SerialReader.PARAMS_PARITY, SerialPort.PARITY_NONE ); // 无奇偶校验
		SerialReader sr = new SerialReader(params);
		jwg = sr.GetJWD();
		return jwg;
	}
	
	
	//更改文件的名称
	public String changeFileName(){
		String newFileName = "";
		DateFormat format = new SimpleDateFormat("yyMMddHHmmssSSS");
        String formatDate = format.format(new java.util.Date());
        newFileName  = formatDate +".jpg";
		return newFileName;
	}
	
	
	//将上传的文件放到指定的目录下面
	public boolean uploadFile(String newFileName,File f){
		String serverPath="uploadfolder/simple/yjdc/image";
		String getFilePath = ServletActionContext.getServletContext().getRealPath("/"+serverPath);
		if(copyFile(getFilePath, newFileName ,f)){
			return true;
		}else{
			return false;
		}
	}
	private boolean copyFile(String uploadpath, String uploadFileFileName, File f) {
			String getfilePath = uploadpath;
	        String newfilename = uploadFileFileName;
	        //要存放的文件对象
	        File uploadFile  = new File(getfilePath+"/"+newfilename);
	        // 复制file对象，实现上传 
	        try {
				FileUtils.copyFile(f,uploadFile);
			} catch (IOException e) {
				e.printStackTrace();
			}
			return true;
	}
	
	
	public void queryYjdc3jbxxBenji() throws UnsupportedEncodingException, IOException{
		HttpServletRequest request = ServletActionContext.getRequest();
		String startTime = request.getParameter("startTime");
		String endTime = request.getParameter("endTime");
		String name = request.getParameter("name");
		String hql = "select distinct jb.JBQK0100,jb.JBQK0110,jb.JBQK0102 from JBQK01 jb,YJDC_YJDC01 yjdc where yjdc.YJDC01000 = jb.JBQK0100 and yjdc.JBQK0102 = jb.JBQK0102 and yjdc.YJDC01380 = 'false'";
		if(!startTime.equals("")){
			hql = hql + " and yjdc.YJDC01270>'"+startTime+"'";
		}
		if(!endTime.equals("")){
			hql = hql + " and yjdc.YJDC01270<'"+endTime+"'";
		}
		if(!name.equals("")){
			hql = hql + " and jb.JBQK0110 like '%"+name+"%'";
		}
		
		List list = DbTools.findBySql(hql);
		JSONArray jsonArray = new JSONArray();
		if(list.size()>0){
			for(int i = 0;i<list.size();i++){
				jsonArray.add(list.get(i));
			}
		}
		ServletActionContext.getResponse().getOutputStream().write(jsonArray.toString().getBytes("utf-8"));
	}
	
	public void queryYjdc3jbxxByTybh() throws UnsupportedEncodingException, IOException{
		HttpServletRequest request = ServletActionContext.getRequest();
		String tybh = request.getParameter("tybh");
		String startTime = request.getParameter("startTime");
		String endTime = request.getParameter("endTime");
		String biaoshi = request.getParameter("biaoshi");
		String hql = "from YjdcYjdc01 where yjdc01000 = '"+tybh+"' and jbqk0102 = '"+biaoshi+"'";
		if(!startTime.equals("")){
			hql = hql +" and yjdc01270>'"+startTime+"'";
		}
		if(!endTime.equals("")){
			hql = hql +" and yjdc01270<'"+endTime+"'";
		}
		hql = hql +"and yjdc01380 = 'false' order by yjdc01270";
		List<YjdcYjdc01> list = DbTools.findByHql(hql);
		JSONArray jsonArray = new JSONArray();
		if(list.size()>0){
			for(int i = 0;i<list.size();i++){
				jsonArray.add(list.get(i));
			}
		}
		ServletActionContext.getResponse().getOutputStream().write(jsonArray.toString().getBytes("utf-8"));
	}
	
	//编辑完了之后，进行保存
	public void jbxxUpdateForYjdc3() throws UnsupportedEncodingException, IOException{
		HttpServletRequest request = ServletActionContext.getRequest();
		String yjdc01140 = request.getParameter("yjdc01140");
		String yjdc01330 = request.getParameter("yjdc01330");
		String jbqk0102 = request.getParameter("jbqk0102");
		yjdc01.setYjdc01140(yjdc01140);
		yjdc01.setYjdc01330(yjdc01330);
		yjdc01.setJbqk0102(jbqk0102);
		yjdc01.setYjdc01380("false");
		if(DbTools.updateObj(yjdc01)){
			ServletActionContext.getResponse().getOutputStream().write("true".getBytes("utf-8"));
		}else{
			ServletActionContext.getResponse().getOutputStream().write("false".getBytes("utf-8"));
		}
	}
	
	public void changeFlagByShangchuan() throws UnsupportedEncodingException, IOException{
		HttpServletRequest request = ServletActionContext.getRequest();
		String yjdc01140 = request.getParameter("yjdc01140");
		String yjdc01330 = request.getParameter("yjdc01330");
		yjdc01.setYjdc01140(yjdc01140);
		yjdc01.setYjdc01330(yjdc01330);
		yjdc01.setYjdc01380("true");
		Object jsoncallback = request.getParameter("jsoncallback");
		if(DbTools.updateObj(yjdc01)){
			String str = jsoncallback+"('true')";
			ServletActionContext.getResponse().getOutputStream().write(str.getBytes("utf-8"));;
		}else{
			String str = jsoncallback+"('false')";
			ServletActionContext.getResponse().getOutputStream().write(str.getBytes("utf-8"));
		}
	}
	
	
	//////////////////////////关于快报////////////////////////////////////
	public void createKbWordToBenjiAnd3G() throws UnsupportedEncodingException, IOException{
		HttpServletRequest request = ServletActionContext.getRequest();
		String id = request.getParameter("id");
		//3g服务器
		String inter = request.getParameter("inter");
		String hql = "from YjdcYjdc01 where id="+id;
		List<YjdcYjdc01> list = DbTools.findByHql(hql);
		YjdcYjdc01 yjdc1 = list.get(0);
		//开始在本机生成word
		boolean flagKb = false;
		boolean flagDcbg = false;
		boolean flagJb = false;
		boolean sendFlag = false;
		try {
			//制造有内容的快报
			flagKb = createWordByKB(yjdc1,"02");
			flagJb = createWordByIsnotKB(yjdc1,"03");//简报
			flagDcbg = createWordByIsnotKB(yjdc1,"00");//调查报告
			if(flagKb&&flagJb&&flagDcbg){//代表在本机生成成功了，那么此时向后台发送请求,将word搞过去
				String tongyibianhao = yjdc1.getYjdc01000();
				DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
				String diaochashijian = format.format(yjdc1.getYjdc01270());
				String zhdBiaoshi = yjdc1.getJbqk0102();
				String wordName = tongyibianhao+"-"+zhdBiaoshi+"-"+diaochashijian+"-02"+".doc";//传递快报过去
				sendFlag = sendKbWordTo3GServlet(wordName,inter);
				
			}
		} catch (DocumentException e) {
			System.out.println(e);
		} catch (IOException e) {
			System.out.println(e);
		}
		
		if(sendFlag&&flagKb&&flagJb&&flagDcbg){
			ServletActionContext.getResponse().getOutputStream().write("true".getBytes("utf-8"));
		}else{
			ServletActionContext.getResponse().getOutputStream().write("false".getBytes("utf-8"));
		}
	}
	
	public boolean sendKbWordTo3GServlet(String docName,String inter){
		boolean flag = false;
		String sendUrl = inter+"/servlet/YjdcKbServletFor3G";
		String filePath = "C:\\kbForPB";
		File wordFile = new File(filePath+"/"+docName);
		PostMethod filePost = new PostMethod(sendUrl);
		try {
			Part[] parts = { new FilePart(wordFile.getName(), wordFile) };
			filePost.setRequestEntity(new MultipartRequestEntity(parts,filePost.getParams()));
		    HttpClient client = new HttpClient();
		    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
		    int status = client.executeMethod(filePost);
		    if (status == HttpStatus.SC_OK)
		    {
		     // 上传成功
		    	flag = true;
		    }
		} catch (FileNotFoundException e) {
			return flag;
		} catch (HttpException e) {
			return flag;
		} catch (IOException e) {
			return flag;
		}
		return flag;
	}
	
	//工作内容，生成快报，在C:/kbForPB下
	public boolean createWordByKB(YjdcYjdc01 yjdc1,String leixing) throws DocumentException, IOException{
		//
		String uploadPath = "C:\\kbForPB"; // 存放文件的目录
		File uploadFile = new File(uploadPath);
        if (!uploadFile.exists()) {
            uploadFile.mkdirs();
        }
		String serverPath="uploadfolder/simple/yjdc/image";
		String getFilePath = ServletActionContext.getServletContext().getRealPath("/"+serverPath);
		String tongyibianhao = yjdc1.getYjdc01000();
		String zhdBiaoshi = yjdc1.getJbqk0102();
		DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		String diaochashijian = format.format(yjdc1.getYjdc01270());
		Document document = new Document(PageSize.A4);
		RtfWriter2.getInstance(document, new FileOutputStream(uploadPath+"/"+tongyibianhao+"-"+zhdBiaoshi+"-"+diaochashijian+"-"+leixing+".doc"));
		document.open();
		BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);  
		Font titleFont = new Font(bfChinese, 12, Font.BOLD);  
		Font contextFont = new Font(bfChinese, 11, Font.NORMAL); 
		
		Paragraph title = new Paragraph("快报");  
		title.setAlignment(Element.ALIGN_CENTER);  
		title.setFont(titleFont);  
		document.add(title);
		//开始制作正文
		String contextString = createContextString(yjdc1);
		Paragraph context = new Paragraph(contextString);  
		//
		context.setAlignment(Element.ALIGN_LEFT);  
		context.setFont(contextFont);  
		context.setSpacingBefore(20);  
		context.setFirstLineIndent(20);  
		document.add(context);  
		//图片一
		if(yjdc1.getYjdc01300()!=""){
			String contextStr1 = "全貌图：";
			Paragraph context1 = new Paragraph(contextStr1);  
			context1.setAlignment(Element.ALIGN_LEFT);  
			context1.setFont(contextFont);  
			context1.setSpacingBefore(20);  
			context1.setFirstLineIndent(20);  
			document.add(context1);
			try{
				Image png = Image.getInstance(getFilePath+"/"+yjdc1.getYjdc01300()); 
				document.add(png);  
			}catch (Exception e) {
				// TODO: handle exception
			}
			
			
		}
		//图片二
		if(yjdc1.getYjdc01300()!=""){
			String contextStr1 = "局部变形图一：";
			Paragraph context1 = new Paragraph(contextStr1);  
			context1.setAlignment(Element.ALIGN_LEFT);  
			context1.setFont(contextFont);  
			context1.setSpacingBefore(20);  
			context1.setFirstLineIndent(20);  
			document.add(context1);  
			try{
				Image png = Image.getInstance(getFilePath+"/"+yjdc1.getYjdc01310()); 
				document.add(png); 
			}catch (Exception e) {
				// TODO: handle exception
			}
			 
		}
		//图片三
		if(yjdc1.getYjdc01300()!=""){
			String contextStr1 = "局部变形图二：";
			Paragraph context1 = new Paragraph(contextStr1);  
			context1.setAlignment(Element.ALIGN_LEFT);  
			context1.setFont(contextFont);  
			context1.setSpacingBefore(20);  
			context1.setFirstLineIndent(20);  
			document.add(context1);  
			try{
				Image png = Image.getInstance(getFilePath+"/"+yjdc1.getYjdc01320()); 
				document.add(png); 
			}catch (Exception e) {
			}
		}
		
		document.close();
		return true;
	}
	
	//工作内容，生成简报、调查报告，在C:/kbForPB下
	public boolean createWordByIsnotKB(YjdcYjdc01 yjdc1,String leixing){
		String uploadPath = "C:\\kbForPB"; // 存放文件的目录
		File uploadFile = new File(uploadPath);
        if (!uploadFile.exists()) {
            uploadFile.mkdirs();
        }
		String tongyibianhao = yjdc1.getYjdc01000();
		String zhdBiaoshi = yjdc1.getJbqk0102();
		DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		String diaochashijian = format.format(yjdc1.getYjdc01270());
		Document document = new Document(PageSize.A4);
		try {
			RtfWriter2.getInstance(document, new FileOutputStream(uploadPath+"/"+tongyibianhao+"-"+zhdBiaoshi+"-"+diaochashijian+"-"+leixing+".doc"));
			document.open();
			BaseFont bfChinese;
			try {
				bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
				Font titleFont = new Font(bfChinese, 12, Font.BOLD);  
				
				Paragraph title = new Paragraph(leixing);  
				title.setAlignment(Element.ALIGN_CENTER);  
				title.setFont(titleFont);  
				try {
					document.add(title);
					document.close();
				} catch (DocumentException e) {
					return false;
				}
			} catch (DocumentException e) {
				return false;
			} catch (IOException e) {
				return false;
			}  
		} catch (FileNotFoundException e) {
			return false;
		}
		return true;
	}
	
	
	public String  createContextString(YjdcYjdc01 yjdc1){
		String content = "";
		DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		String fashengshijian = yjdc1.getYjdc01010()==null?"":format.format(yjdc1.getYjdc01010());
		String diliweizhi = yjdc1.getYjdc01030();
		String guimodengjiNumber = yjdc1.getYjdc01240();
		String guimodengji = "";
		if("4".equals(guimodengjiNumber))
			guimodengji = "小型";
		if("3".equals(guimodengjiNumber))
			guimodengji = "中型";
		if("2".equals(guimodengjiNumber))
			guimodengji = "大型";
		if("1".equals(guimodengjiNumber))
			guimodengji = "特大型";
		String tongyibianhao = yjdc1.getYjdc01000();
		String zaihaileixingNumber = tongyibianhao.substring(6,8);
		String zaihaileixingStr = "";
		if("00".equals(zaihaileixingNumber))
			zaihaileixingStr = "斜坡变形";
		if("01".equals(zaihaileixingNumber))
			zaihaileixingStr = "滑坡";
		if("02".equals(zaihaileixingNumber))
			zaihaileixingStr = "崩塌";
		if("03".equals(zaihaileixingNumber))
			zaihaileixingStr = "泥石流";
		if("04".equals(zaihaileixingNumber))
			zaihaileixingStr = "岩溶塌陷";
		if("05".equals(zaihaileixingNumber))
			zaihaileixingStr = "采空塌陷";
		if("06".equals(zaihaileixingNumber))
			zaihaileixingStr = "地裂缝";
		if("07".equals(zaihaileixingNumber))
			zaihaileixingStr = "地面沉降";
		if("08".equals(zaihaileixingNumber))
			zaihaileixingStr = "塌岸";
		if("09".equals(zaihaileixingNumber))
			zaihaileixingStr = "高切坡";
		if("10".equals(zaihaileixingNumber))
			zaihaileixingStr = "危岩体";
		String qianyuangaocheng = yjdc1.getYjdc01040()==null?"":yjdc1.getYjdc01040().toString();
		String houyuangaocheng = yjdc1.getYjdc01050()==null?"":yjdc1.getYjdc01050().toString();
		String mianji = yjdc1.getYjdc01120()==null?"":yjdc1.getYjdc01120().toString();
		String tiji = yjdc1.getYjdc01130()==null?"":yjdc1.getYjdc01130().toString();
		String zhijiejingji = yjdc1.getYjdc01170()==null?"":yjdc1.getYjdc01170().toString();
		String qianzaijingji = yjdc1.getYjdc01200()==null?"":yjdc1.getYjdc01200().toString();
		String siwangrenshu = yjdc1.getYjdc01180()==null?"":yjdc1.getYjdc01180().toString();
		String weixierenshu = yjdc1.getYjdc01190()==null?"":yjdc1.getYjdc01190().toString();
		String shizongrenshu = yjdc1.getYjdc01181()==null?"":yjdc1.getYjdc01181().toString();
		String shoushangrenshu = yjdc1.getYjdc01182()==null?"":yjdc1.getYjdc01182().toString();
		String diaocharen = yjdc1.getYjdc01250()==null?"":yjdc1.getYjdc01250();
		String diaochadanwei = yjdc1.getYjdc01260()==null?"":yjdc1.getYjdc01260();
		String diaochashijian = format.format(yjdc1.getYjdc01270());
		content = "发生时间"+fashengshijian+"，在"+diliweizhi+"发生"+guimodengji+"的"+zaihaileixingStr+"地质灾害，"+
						"前缘高程为："+qianyuangaocheng+"米，后缘高程为："+houyuangaocheng+"米，面积为"+mianji+"平方米，"+
						"体积为："+tiji+"立方米，直接经济损失"+zhijiejingji+"万元，潜在损失"+qianzaijingji+"万元，死亡人数为"+
						siwangrenshu+"人，威胁人数为"+weixierenshu+"，失踪人数为"+shizongrenshu+"人，受伤人数为"+shoushangrenshu+
						"人，调查人："+diaocharen+"，调查单位："+diaochadanwei+"，调查时间："+diaochashijian+"。";
		return content;
	}
	
}

